<?php

/**
 * RabbitMQ消息队列消费者
 */

namespace common\lib;

Use Yii;

/**
 * RabbitMQ消息队列生产者
 */
class RabbitMQ extends \yii\base\Component{

    public $host;
    public $port;
    public $user;
    public $password;
    public $vhost;
    public $isTransaction;
//    private $exchangeName = 'ex_huawei';
//    private $queueName = 'queue_huawei';
//    private $routeKey = 'route_huawei';
    private $cn;
    private $ch;
    private $ex;
    private $queue;
    
    public function init() {
        parent::init();
        $this->connect();
    }

    /**
     * 组装参数
     */
    private function connectParams() {
        return ['host' => $this->host, 'port' => $this->port, 'login' => $this->user, 'password' => $this->password, 'vhost' => $this->vhost];
    }

    /**
     * 连接队列服务器并创建channel
     */
    private function connect() {
        $params = $this->connectParams();
        $this->cn = new \AMQPConnection($params);
        if (!$this->cn->connect()) {die("不能连接这个BROCKER\n");}
        $this->channel();
    }
    
    /**
     * 信道定义
     */
    private function channel(){
        $this->ch = new \AMQPChannel($this->cn);
    }

    /**
     * 创建交换机
     */
    private function exchange($exchangeName) {
        $this->ex = new \AMQPExchange($this->ch);
        $this->ex->setName($exchangeName);
        date_default_timezone_set("Asia/Shanghai");
    }
    
    /**
     * 创建队列并绑定交换机
     */
    private function queue($queueName) {
        //使用哪个信道
        $this->queue = new \AMQPQueue($this->ch);
        $this->queue->setName($queueName);
        $this->queue->setFlags(AMQP_DURABLE);
//        echo "Message Total:".$this->queue->declare()."\n";   
//        $this->queue->bind($this->exchangeName, $this->routeKey);
    }
    
    private function disconnect(){
        $this->cn->disconnect();
    }


    /**
     * 生产者方法 - 单条
     * @param type $msg
     * @return type
     */
    public function sendOne($msg, $exchangeName, $routeKey){
        $this->exchange($exchangeName);
        return $this->ex->publish($msg, $routeKey);
    }
    
    /**
     * 生产者方法 - 多条
     * @param type $msgs
     * @return type
     */
    public function sendMultiple($msgs, $exchangeName, $routeKey){
        $this->exchange($exchangeName);
        if ($this->isTransaction) {$this->ch->startTransaction();}//如果启用事务$
        $result = [];
        foreach($msgs as $k => $msg){
            $result[$k] = $this->ex->publish($msg, $routeKey);
        }
        if ($this->isTransaction) {$this->ch->commitTransaction();}//如果启用事务
        return $result;
    }
    
    /**
     * 消费者方法
     * 这里需要根据相应的业务逻辑进行修改
     */
    public function getQueue($queueName) {
        $this->queue($queueName);
        return $this->queue;
    }
}
